# -*- coding:UTF-8 -*-

from dingtalkchatbot.chatbot import DingtalkChatbot
import pandas as pd
import numpy as np
import emoji
import sys
import threading
import time
import asyncio
import re
import json
import gc
import os

sys.path.append('..')
from util.TimeStamp import TimeTamp
from okexApi._websocket import PublicSocketApi
from okexApi._http import HttpApi
from sqlHandler import SqlHandler
import threading


class Trading(threading.Thread):
    def __init__(self, candle, user_info=None):
        threading.Thread.__init__(self)
        if not user_info:
            print('请填写用户信息')
            return

        self.table_name = candle + '_table_' + user_info['symbol'].split('-')[0]
        self.publicSocketApi = PublicSocketApi(on_created=None,
                                               on_message=self._router,
                                               on_closed=self.restart,
                                               candle=candle,
                                               user_info=user_info)  # 初始化长连接
        self.http = HttpApi(user_info=user_info)  # 初始化短连接
        self.timeTamp = TimeTamp()  # 初始化时间操作对象
        self.sqlHandler = SqlHandler(  # 初始化数据库操作对象
            ip=user_info['ip'],
            userName=user_info['userName'],
            userPass=user_info['userPass'],
            DBName=user_info['DBName'],
            charset=user_info['charset'],
        )

        self.old_kl = []
        # 对照字典表
        self.channel_Dict = {
            "candle": self.breathing,  # 走 行情检测 函数
        }

    # 推送路由
    def _router(self, res):
        def query(channel):
            if channel in self.channel_Dict:
                return self.channel_Dict[channel]
            elif re.search('candle', channel).group():
                return self.channel_Dict['candle']
            else:
                print('调用错误')
                return False

        # okex 回调数据
        channel = res['arg']['channel']
        # 如果回调数据 data长度为0，说明暂无数据，调用无效
        if len(res['data']) == 0:
            return
        else:
            data = res['data'][0]
            _fun = query(channel)
            _fun(data)

    # 重启策略
    def restart(self, _res):
        name = _res['data']
        print(name + '新家园建立')
        if name == 'public':
            time.sleep(3)
            self.publicSocketApi.subscription()

    # 主函数
    def run(self):
        table_list = self.sqlHandler.select_all_table()
        if not self.table_name in table_list:
            self.sqlHandler.create_table(self.table_name)
        self.publicSocketApi.subscription()

    def breathing(self, kline_data):
        # 判断新老数据
        # 第一次进入循环 或者 同一时间的老数据，都会进入
        if kline_data[0] in self.old_kl:
            # 其实可以完全不写下面的代码，但是意义就不一样了。
            self.old_kl = kline_data
            return
        else:
            # 防止数据为初始化就走下面的逻辑
            if len(self.old_kl) == 0:
                self.old_kl = kline_data
                return

            _k = pd.DataFrame([self.old_kl]).astype(float)
            _k.columns = [
                'id_tamp', 'open_price', 'high_price', 'lowest_price',
                'close_price', 'vol', 'volCcy'
            ]

            KLINE_DATA = _k.to_dict('records')[0]
            # 装车
            self.sqlHandler.insert_trade_marks_data(KLINE_DATA,
                                                    self.table_name)
            self.old_kl = kline_data


if __name__ == "__main__":
    # 获取要执行的用户配置
    f = open('../config.json', 'r', encoding='utf-8')
    _data = json.load(f)
    _ulist = _data
    print('我的进程id 是 ', os.getpid())
    for symbol in _ulist:
        for item in symbol['task_library']:
            
            trading = Trading(candle=item, user_info=symbol)
            trading.start()
